/// API服务
/// 提供与后端API的通信
library;

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:chat_project/config/api_config.dart';
import 'package:chat_project/services/storage_service.dart';

class ApiService {
  final StorageService _storageService = StorageService();
  final bool _useMockData = true; // 临时使用模拟数据进行测试

  // HTTP客户端
  http.Client get _client => http.Client();

  // 设置请求头
  Future<Map<String, String>> _getHeaders() async {
    final token = await _storageService.getToken();
    return {
      'Content-Type': 'application/json',
      'Authorization': token != null ? 'Bearer $token' : '',
    };
  }

  // 处理响应
  dynamic _handleResponse(http.Response response) {
    if (response.statusCode >= 200 && response.statusCode < 300) {
      if (response.body.isEmpty) return null;
      return json.decode(response.body);
    } else {
      final error = json.decode(response.body);
      throw error['message'] ?? '请求失败';
    }
  }

  // 获取用户会话列表
  Future<List<dynamic>> getConversations() async {
    if (_useMockData) {
      await Future.delayed(const Duration(seconds: 1)); // 模拟网络延迟

      final List<Map<String, dynamic>> mockConversations = [];

      // 模拟10个对话
      for (int i = 1; i <= 10; i++) {
        final username = 'user$i';

        mockConversations.add({
          'id': 'conv_$i',
          'contact': {
            'id': 'user_$i',
            'username': username,
            'email': '$username@example.com',
            'avatar':
                'https://ui-avatars.com/api/?name=$username&background=random&format=png',
            'isOnline': i % 3 == 0, // 每3个用户中有1个在线
            'lastSeen': DateTime.now()
                .subtract(Duration(minutes: i * 5))
                .toIso8601String(),
          },
          'lastMessage': i % 4 == 0
              ? null
              : {
                  'id': 'msg_${i}_${DateTime.now().millisecondsSinceEpoch}',
                  'content': '这是一条测试消息 $i',
                  'type': 'text',
                  'sender': {
                    'id': i % 2 == 0 ? '1' : 'user_$i',
                    'username': i % 2 == 0 ? 'user1' : username,
                    'avatar': i % 2 == 0
                        ? 'https://ui-avatars.com/api/?name=user1&background=random&format=png'
                        : 'https://ui-avatars.com/api/?name=$username&background=random&format=png',
                  },
                  'createdAt': DateTime.now()
                      .subtract(Duration(minutes: i * 10))
                      .toIso8601String(),
                  'status': 'delivered',
                },
          'unreadCount': i % 3 == 0 ? i : 0, // 有些对话有未读消息
          'updatedAt': DateTime.now()
              .subtract(Duration(minutes: i * 10))
              .toIso8601String(),
        });
      }

      return mockConversations;
    }
    return [];

    // ... existing code ...
  }

  // 获取与特定用户的消息历史
  Future<List<dynamic>> getMessages(String userId) async {
    if (_useMockData) {
      await Future.delayed(const Duration(seconds: 1)); // 模拟网络延迟

      final List<Map<String, dynamic>> mockMessages = [];

      // 模拟20条消息记录
      for (int i = 1; i <= 20; i++) {
        final isSelf = i % 2 == 0;
        final username = isSelf ? 'user1' : 'user$userId';
        final timestamp =
            DateTime.now().subtract(Duration(minutes: (20 - i) * 10));

        mockMessages.add({
          'id': 'msg_${i}_${timestamp.millisecondsSinceEpoch}',
          'content': '这是第 $i 条测试消息',
          'type': 'text',
          'sender': {
            'id': isSelf ? '1' : userId,
            'username': username,
            'avatar':
                'https://ui-avatars.com/api/?name=$username&background=random&format=png',
          },
          'receiverId': isSelf ? userId : '1',
          'status': 'read',
          'createdAt': timestamp.toIso8601String(),
        });
      }

      return mockMessages;
    }
    return [];

    // ... existing code ...
  }

  // 发送消息
  Future<Map<String, dynamic>> sendMessage(
      String receiverId, String content, String type) async {
    if (_useMockData) {
      await Future.delayed(const Duration(seconds: 1)); // 模拟网络延迟

      final timestamp = DateTime.now();
      return {
        'id': 'msg_${timestamp.millisecondsSinceEpoch}',
        'content': content,
        'type': type,
        'sender': {
          'id': '1',
          'username': 'user1',
          'avatar': 'https://ui-avatars.com/api/?name=user1&background=random&format=png',
        },
        'receiverId': receiverId,
        'status': 'sent',
        'createdAt': timestamp.toIso8601String(),
      };
    }
        return {};

    // ... existing code ...
  }

  // 用户登录
  Future<Map<String, dynamic>> login(String username, String password) async {
    if (_useMockData) {
      await Future.delayed(const Duration(seconds: 1)); // 模拟网络延迟
      
      // 在模拟模式下，任何用户名和密码都允许登录
      // 简单验证，密码至少需要6个字符
      if (password.length < 6) {
        throw '密码至少需要6个字符';
      }
      
      final mockToken = 'mock_token_${DateTime.now().millisecondsSinceEpoch}';
      
      // 保存令牌到本地存储
      await _storageService.saveToken(mockToken);
      
      return {
        '_id': '1',
        'username': username,
        'email': '$username@example.com',
        'avatar': 'https://ui-avatars.com/api/?name=${username[0]}&background=random&format=png',
        'token': mockToken,
      };
    }

    try {
      final response = await _client.post(
        Uri.parse(ApiConfig.loginUrl),
        headers: {'Content-Type': 'application/json'},
        body: json.encode({
          'usernameOrEmail': username,
          'password': password,
        }),
      );
      
      final data = _handleResponse(response);
      
      // 确保数据中包含token
      if (data['token'] != null) {
        print('获取到令牌: ${data['token'].substring(0, 10)}...');
        // 保存令牌到本地存储
        await _storageService.saveToken(data['token']);
      } else {
        print('警告: 后端返回数据中不包含token');
      }
      
      return data;
    } catch (e) {
      print('登录失败: $e');
      rethrow;
    }
  }

  // 用户注册
  Future<Map<String, dynamic>> register(
      String username, String email, String password) async {
    if (_useMockData) {
      await Future.delayed(const Duration(seconds: 1)); // 模拟网络延迟
      
      // 在模拟模式下，执行基本验证
      if (username.length < 3) {
        throw '用户名至少需要3个字符';
      }
      
      if (password.length < 6) {
        throw '密码至少需要6个字符';
      }
      
      final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
      if (!emailRegex.hasMatch(email)) {
        throw '请输入有效的邮箱地址';
      }
      
      final mockToken = 'mock_token_${DateTime.now().millisecondsSinceEpoch}';
      
      // 保存令牌到本地存储
      await _storageService.saveToken(mockToken);
      
      return {
        '_id': '1',
        'username': username,
        'email': email,
        'avatar': 'https://ui-avatars.com/api/?name=${username[0]}&background=random&format=png',
        'token': mockToken,
      };
    }

    try {
      final response = await _client.post(
        Uri.parse(ApiConfig.registerUrl),
        headers: {'Content-Type': 'application/json'},
        body: json.encode({
          'username': username,
          'email': email,
          'password': password,
        }),
      );
      
      final data = _handleResponse(response);
      
      // 确保数据中包含token
      if (data['token'] != null) {
        print('获取到令牌: ${data['token'].substring(0, 10)}...');
        // 保存令牌到本地存储
        await _storageService.saveToken(data['token']);
      } else {
        print('警告: 后端返回数据中不包含token');
      }
      
      return data;
    } catch (e) {
      print('注册失败: $e');
      rethrow;
    }
  }

  // 获取当前用户信息
  Future<Map<String, dynamic>> getCurrentUser() async {
    if (_useMockData) {
      await Future.delayed(const Duration(seconds: 1)); // 模拟网络延迟
      const username = 'user1';
      return {
        '_id': '1',
        'username': username,
        'email': '$username@example.com',
        'avatar': 'https://ui-avatars.com/api/?name=$username&background=random&format=png',
        'bio': '这是一个测试用户',
        'isOnline': true,
        'lastSeen': DateTime.now().toIso8601String(),
      };
    }
        return {};

    // ... existing code ...
  } 
} 